#coding:utf-8
'''
* coder  : Dzlua
* email  : 505544956@qq.com
* module : api-frame
* path   : app/utils
* file   : base.py
* time   : 2017/10/22
'''
#--------------------#
import os
#--------------------#

#--------------------#
def is_file(name):
    return os.path.isfile(name)
#----------#
def is_dir(name):
    return os.path.isdir(name)
#----------#
def is_exist(name):
    return os.path.exists(name)
#----------#
def dir_name(file):
    return os.path.dirname(file)
#----------#
def file_name(file):
    return os.path.basename(file)
#----------#
def file_join(dir, file):
    return os.path.join(dir, file)
#----------#
def module_dir():
    return os.getcwd()
#----------#
def mkdirs(path):
    try:
        os.makedirs(path)
    except:
        pass
#----------#
def create_file(file, content=''):
    if is_exist(file):
        print('Tips: exist file. ' + file)
        return False
    path = dir_name(file)
    mkdirs(path)
    #
    fp = open(file, 'w')
    fp.write(content)
    fp.close()

    return True
#--------------------#

#--------------------#
def get_space(num):
    space = ''
    for i in range(0, num):
        space += ' '
    return space
#----------#
def get_input(tip, default=None, required=False, space=0):
    prefx = get_space(space)
    tail = ''
    try:
        tail = ' (default:' + default + '): '
    except:
        pass
    #
    if not required:
        return raw_input(prefx + tip + tail) or default
    while (True):
        data = raw_input(prefx + tip)
        if data:
            return data
#----------#
def choice_input(tip, choice, default=0, required=False, space=0):
    prefx = get_space(space)
    def _get_input(tip):
        try:
            return int(input(tip))
        except:
            return None
    def is_in(i):
        if i is None:
            return False
        if i < 0:
            return False
        elif i >= len(choice):
            return False
        return True
    def show(tip):
        print(prefx + tip)
        i = 0
        for v in choice:
            if default == i and not required:
                print(prefx + prefx + str(i) + ': ' + v + ' (default)')
            else:
                print(prefx + prefx + str(i) + ': ' + v)
            i += 1
    if not required:
        show('select database type: ')
        ret = _get_input(prefx + ' select: ') or default
        if is_in(ret):
            return choice[ret]
        else:
            return choice[default]
    else:
        while(True):
            show('select database type: ')
            ret = _get_input(prefx + 'select: ')
            if is_in(ret):
                return choice[ret]
#--------------------#

#--------------------#
